package com.recruit.g1.user.service.impl;

import com.recruit.g1.common.response.JsonResult;
import com.recruit.g1.common.response.StateCode;
import com.recruit.g1.pojo.passport.param.UserLoginParam;
import com.recruit.g1.pojo.user.dto.UserRegParam;
import com.recruit.g1.pojo.user.entity.User;
import com.recruit.g1.pojo.user.vo.UserSaveParam;
import com.recruit.g1.user.dao.mapper.UserMapper;
import com.recruit.g1.user.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

//    @Autowired
//    private UserService userService;

    @Override
    public JsonResult register(UserRegParam userRegParam) {
        UserSaveParam userSaveParam = userMapper.selectByUsername(userRegParam.getUsername());

        log.debug("完成selectByUsername");
        if (userSaveParam!=null){
            return JsonResult.fail(StateCode.USERNAME_EXISTS);
        }

        userMapper.insert(userRegParam);
        log.debug("注册数据："+userRegParam);
        return JsonResult.ok("注册成功！");
    }


    private static final Logger log = LogManager.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired private RedisTemplate redisTemplate;
    @Override
    public JsonResult login(UserLoginParam userLoginParam) {
        // 1. 执行数据库查询
        User user = userMapper.selectByUsernameAndPassword(
                userLoginParam.getUsername(),
                userLoginParam.getPassword()
        );

        // 2. 打印日志（关键调试信息）
        System.out.println("数据库查询结果: " + user);

        // 3. 用户不存在或密码错误
        if (user == null) {
            System.out.println("登录失败：用户名或密码错误");
            return JsonResult.fail(StateCode.USERNAME_PASSWORD_ERROR);
        }

        // 4. 登录成功 →  Token（新增！）
        String token =  UUID.randomUUID().toString().replace("-", "");
        System.out.println("生成的Token：" + token);
        // 5. 存储Token到Redis（新增！Key格式：token:xxx，Value：用户ID）
        redisTemplate.opsForValue().set(
                "token:" + token,          // Redis的Key
                String.valueOf(user.getId()), // Redis的Value（存用户ID）
                Duration.ofHours(1)        // 过期时间1小时
        );
        redisTemplate.opsForValue().set(
                "userID:" + user.getId(),
                "userName:"+user.getUsername(),
                Duration.ofHours(1)
        );
        // 6. 清除敏感信息（原有逻辑保留）
        user.setPassword("");

        // 7. 构造返回结果（返回Token和用户信息）
        Map<String, Object> data = new HashMap<>();
        data.put("user", user);  // 用户信息
        data.put("token", token); // Token字段（前端需存储）
        JsonResult result = JsonResult.ok(data);

        // 8. 打印最终返回结果（必须！）
        System.out.println("返回给前端的JsonResult: " + result);
        return result;
    }

    @Override
    public Map<String, Object> getUserInfoByToken(String token) {
        String tokenKey = "token:" + token;
        Object userIdObj = redisTemplate.opsForValue().get(tokenKey);

        if (userIdObj == null) {
            return null; // Token 不存在或过期
        }

        String userIdStr = userIdObj.toString();
        Long userId = Long.valueOf(userIdStr);

        String userKey = "userID:" + userId;
        Object usernameWithPrefix = redisTemplate.opsForValue().get(userKey);

        if (usernameWithPrefix == null) {
            return null; // 用户信息不存在
        }

        String username = usernameWithPrefix.toString().replace("userName:", "");

        Map<String, Object> result = new HashMap<>();
        result.put("id", userId);
        result.put("username", username);

        return result;
    }


    /**
     * 重置密码(修改密码)
     * @param newPassword
     * @param httpSession
     * @return
     */
    @Override
    public JsonResult resetPassword(String newPassword,@ApiIgnore HttpSession httpSession) {
        UserSaveParam userSaveParam = (UserSaveParam) httpSession.getAttribute("currentLoginUser");
        if (userSaveParam==null){
            return JsonResult.fail(StateCode.NOT_LOGIN);
        }
        int result =
        userMapper.updatePassword(userSaveParam.getUsername(), userSaveParam.getPassword() ,newPassword);

        if (result==1){
            return JsonResult.ok("修改密码成功");
        }

        return JsonResult.fail("密码修改失败");
    }
}
